const fs = require('fs');
const path = require('path');

async function getAllFile(directoryPath) {
  return {
    filelist: getFilesAndSizes(directoryPath),
    dirpath: directoryPath,
    size: formatSize(getFolderSize(directoryPath))
  }
}
function formatSize(sizeInBytes) {
  const units = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
  let unitIndex = 0;
  let size = sizeInBytes;

  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024;
    unitIndex++;
  }

  return `${size.toFixed(2)} ${units[unitIndex]}`;
}

// 递归获取文件夹下所有文件的路径和大小
function getFilesAndSizes(folderPath) {
  let result = [];

  // 读取目录中的文件和子目录
  const items = fs.readdirSync(folderPath);

  items.forEach(item => {
    const fullPath = path.join(folderPath, item);
    const stats = fs.statSync(fullPath); // 获取文件或目录的统计信息

    if (stats.isDirectory()) {
      // 如果是目录，递归获取该目录下的文件
      result = result.concat(getFilesAndSizes(fullPath));
    } else {
      // 如果是文件，记录文件路径和大小
      if (fullPath.indexOf("tif") != -1) {
        result.push({ filepath: fullPath, size: formatSize(stats.size), filename: item });
      }
    }
  });

  return result;
}

// 递归计算文件夹大小
function getFolderSize(folderPath) {
  let totalSize = 0;

  // 读取目录中的文件和子目录
  const items = fs.readdirSync(folderPath);

  items.forEach(item => {
    const fullPath = path.join(folderPath, item);
    const stats = fs.statSync(fullPath);

    if (stats.isDirectory()) {
      // 如果是子目录，递归调用
      totalSize += getFolderSize(fullPath);
    } else {
      // 如果是文件，累加文件大小
      if (fullPath.indexOf("tif") != -1) {
        totalSize += stats.size;
      }
    }
  });

  return totalSize;
}



exports.getAllFile = getAllFile